<template>
  <div class="input-panel">
    <!-- 文件预览 -->
    <div v-if="selectedFiles.length > 0" class="file-preview">
      <!-- 多张图片预览 -->
      <div class="images-preview-grid">
        <div 
          v-for="(file, index) in selectedFiles" 
          :key="index"
          class="image-preview-item"
        >
          <!-- 图片预览 -->
          <div v-if="isImageFile(file)" class="image-preview-container">
            <img 
              :src="getImagePreviewUrl(file)" 
              :alt="file.name"
              class="preview-image"
              @error="handleImagePreviewError"
            />
            <q-btn
              flat
              dense
              round
              icon="close"
              size="sm"
              class="remove-image-btn"
              @click="$emit('remove-file', index)"
            />
          </div>
          <!-- 非图片文件 -->
          <q-chip
            v-else
            removable
            @remove="$emit('remove-file', index)"
            color="primary"
            text-color="white"
            size="sm"
            class="file-chip"
          >
            <q-icon name="attach_file" size="xs" class="q-mr-xs" />
            <span>{{ file.name }}</span>
          </q-chip>
        </div>
      </div>
    </div>

    <!-- 工具栏按钮区域 -->
    <div class="toolbar-section">
      <!-- 左侧：文件、表情按钮 -->
      <div class="toolbar-left">
        <q-btn 
          flat 
          dense 
          icon="attach_file" 
          @click="handleFileSelect()" 
          class="toolbar-btn"
          size="sm"
          title="选择文件（支持多选）"
          unelevated
        />
        <q-btn 
          flat 
          dense 
          icon="mood" 
          @click="toggleEmojiPicker" 
          class="toolbar-btn"
          size="sm"
          title="表情"
          unelevated
        />
      </div>
      <input
        v-if="!isTauri()"
        ref="fileInputRef"
        type="file"
        style="display: none"
        @change="handleFileSelect"
        accept="*/*"
        multiple
      />
      <div class="emoji-picker-container" v-if="showEmojiPicker">
        <EmojiPicker :visible="showEmojiPicker" @select="handleEmojiSelect" />
      </div>
    </div>

    <!-- 输入框区域 -->
    <div class="input-section">
      <div class="input-wrapper" ref="inputWrapperRef">
        <q-input
          ref="inputContentRef"
          :model-value="inputContent"
          @update:model-value="handleInputUpdate"
          @keydown="handleKeyDown"
          placeholder="输入消息..."
          type="textarea"
          autogrow
          class="message-input"
          autocomplete="off"
          autocapitalize="off"
          autocorrect="off"
          spellcheck="false"
          @keydown.enter.exact.prevent="handleEnterKey"
          @keydown.enter.shift.exact="$emit('shift-enter')"
          :rows="1"
        />
        <!-- @成员选择器 -->
        <MentionPicker
          v-if="showMentionPicker && isGroupChat"
          :visible="showMentionPicker"
          :members="mentionMembers"
          :search-text="mentionSearchText"
          @select="handleMentionSelect"
          @close="closeMentionPicker"
          ref="mentionPickerRef"
        />
      </div>
    </div>

    <!-- 群组详情对话框（已移到抽屉，这里保留但隐藏） -->
    <q-dialog v-model="showGroupDetailsDialog" @show="loadGroupDetails" v-if="false">
      <q-card class="group-details-dialog" style="min-width: 600px; max-width: 800px; max-height: 85vh">
        <q-card-section class="dialog-header">
          <div class="dialog-title">群组详情</div>
          <q-space />
          <q-btn icon="close" flat round dense v-close-popup />
        </q-card-section>
        
        <q-card-section class="dialog-body" style="max-height: calc(85vh - 200px); overflow-y: auto">
          <!-- 群组基本信息 -->
          <div class="group-info-section">
            <div class="group-detail-item">
              <div class="detail-label">群组名称</div>
              <div class="detail-value">{{ currentGroupDetails?.group_name || targetName || '未知' }}</div>
            </div>
            <div class="group-detail-item" v-if="currentGroupDetails?.introduction">
              <div class="detail-label">群组简介</div>
              <div class="detail-value">{{ currentGroupDetails.introduction }}</div>
            </div>
            <div class="group-detail-item">
              <div class="detail-label">群主</div>
              <div class="detail-value">
                <span v-if="isGroupOwner(currentGroupDetails)">您（{{ currentGroupDetails?.owner_id }}）</span>
                <span v-else>{{ currentGroupDetails?.owner_id || '未知' }}</span>
              </div>
            </div>
            <div class="group-detail-item">
              <div class="detail-label">成员数量</div>
              <div class="detail-value">{{ currentGroupDetails?.member_count || groupDetailsMembers.length || 0 }} 人</div>
            </div>
            <div class="group-detail-item">
              <div class="detail-label">群组类型</div>
              <div class="detail-value">{{ currentGroupDetails?.group_type === 1 ? '私有群' : '公开群' }}</div>
            </div>
            <div class="group-detail-item">
              <div class="detail-label">加入方式</div>
              <div class="detail-value">{{ currentGroupDetails?.apply_join_type === 1 ? '需要审批' : '自由加入' }}</div>
            </div>
          </div>

          <!-- 群成员列表 -->
          <div class="members-section">
            <div class="section-header">
              <div class="section-title">
                <q-icon name="people" size="20px" class="q-mr-xs" />
                群成员 ({{ groupDetailsMembers.length }})
              </div>
              <q-input
                v-model="groupDetailsMemberSearch"
                placeholder="搜索成员"
                outlined
                dense
                class="member-search-input"
                autocomplete="off"
                clearable
              >
                <template v-slot:prepend>
                  <q-icon name="search" />
                </template>
              </q-input>
            </div>
            
            <div class="members-list">
              <div v-if="loadingGroupDetailsMembers" class="loading-members">
                <q-spinner color="primary" size="32px" />
                <div class="loading-text">加载成员中...</div>
              </div>
              <div v-else-if="filteredGroupDetailsMembers.length === 0" class="empty-members">
                <q-icon name="people_outline" size="48px" color="grey-5" />
                <div class="empty-text">{{ groupDetailsMemberSearch ? '未找到匹配的成员' : '暂无成员' }}</div>
              </div>
              <div
                v-else
                v-for="member in filteredGroupDetailsMembers"
                :key="member.member_id"
                class="member-item-detail"
              >
                <q-avatar class="member-avatar-detail" size="40px">
                  <div class="avatar-placeholder">
                    {{ (member.alias?.[0] || member.member_id[0] || 'M').toUpperCase() }}
                  </div>
                </q-avatar>
                <div class="member-info-detail">
                  <div class="member-name-detail">
                    {{ member.alias || member.member_id }}
                    <q-chip
                      v-if="member.role === 2"
                      size="sm"
                      color="orange"
                      text-color="white"
                      dense
                      class="q-ml-xs"
                    >
                      群主
                    </q-chip>
                    <q-chip
                      v-else-if="member.role === 1"
                      size="sm"
                      color="primary"
                      text-color="white"
                      dense
                      class="q-ml-xs"
                    >
                      管理员
                    </q-chip>
                  </div>
                  <div class="member-id-detail">{{ member.member_id }}</div>
                </div>
              </div>
            </div>
          </div>
        </q-card-section>

        <!-- 底部操作按钮 -->
        <q-separator />
        <q-card-actions class="dialog-actions-bottom">
          <q-space />
          <q-btn
            flat
            label="关闭"
            @click="showGroupDetailsDialog = false"
            class="dialog-btn"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import EmojiPicker from './EmojiPicker.vue'
import MentionPicker from './MentionPicker.vue'
import { useMessageInput } from './MessageInput'
import { isTauri } from '../services/secure-storage'
import { getGroup, getGroupMembers } from '../services/im-group'
import { getUserAsync, getUser } from '../services/auth'
import { useQuasar } from 'quasar'

const $q = useQuasar()

const props = defineProps<{
  inputContent: string
  sending: boolean
  selectedFiles: File[]
  showEmojiPicker: boolean
  chatType?: number
  currentTargetId?: string | null
  targetType?: 'User' | 'Group'
  targetName?: string
  getUserInitial?: (userId: string | null) => string
}>()

const emit = defineEmits<{
  'update:inputContent': [value: string]
  'update:showEmojiPicker': [value: boolean]
  'send': []
  'enter-key': []
  'shift-enter': []
  'file-select': [file: File]
  'remove-file': [index?: number]
  'emoji-select': [emoji: string]
  'show-group-details': []
}>()

// Refs for template
const inputContentRef = ref<any>(null)
const mentionPickerRef = ref<InstanceType<typeof MentionPicker> | null>(null)

// 群组详情对话框相关
const showGroupDetailsDialog = ref(false)
const currentGroupDetails = ref<any>(null)
const groupDetailsMembers = ref<any[]>([])
const groupDetailsMemberSearch = ref('')
const loadingGroupDetailsMembers = ref(false)
const currentUser = ref<any>(null)

// 加载群组详情
const loadGroupDetails = async () => {
  if (!props.currentTargetId || props.targetType !== 'Group') return
  
  loadingGroupDetailsMembers.value = true
  try {
    // 加载当前用户信息
    if (!currentUser.value) {
      try {
        currentUser.value = await getUserAsync()
      } catch (e) {
        currentUser.value = getUser()
      }
    }
    
    // 加载群组信息
    try {
      const groupInfo = await getGroup(props.currentTargetId)
      currentGroupDetails.value = groupInfo
    } catch (error: any) {
      console.warn('获取群组详情失败:', error)
      // 如果获取失败，使用基本信息
      currentGroupDetails.value = {
        group_id: props.currentTargetId,
        group_name: props.targetName,
        member_count: 0,
      }
    }
    
    // 加载群成员列表
    try {
      const members = await getGroupMembers(props.currentTargetId, false)
      groupDetailsMembers.value = members
      groupDetailsMemberSearch.value = ''
    } catch (error: any) {
      console.error('获取群组成员列表失败:', error)
      groupDetailsMembers.value = []
      $q.notify({
        type: 'warning',
        message: '加载群成员列表失败',
        position: 'top',
      })
    }
  } finally {
    loadingGroupDetailsMembers.value = false
  }
}

// 过滤群成员
const filteredGroupDetailsMembers = computed(() => {
  let filtered = groupDetailsMembers.value
  
  if (groupDetailsMemberSearch.value) {
    const query = groupDetailsMemberSearch.value.toLowerCase()
    filtered = filtered.filter(
      (m) =>
        m.member_id.toLowerCase().includes(query) ||
        (m.alias && m.alias.toLowerCase().includes(query))
    )
  }
  
  return filtered
})

// 判断是否是群主
const isGroupOwner = (group: any): boolean => {
  if (!currentUser.value || !group?.owner_id) {
    return false
  }
  
  const ownerId = String(group.owner_id).trim()
  const userOpenId = currentUser.value.open_id ? String(currentUser.value.open_id).trim() : ''
  const userSnowflakeId = currentUser.value.snowflake_id ? String(currentUser.value.snowflake_id).trim() : ''
  const userId = String(currentUser.value.id).trim()
  const userName = currentUser.value.name ? String(currentUser.value.name).trim() : ''
  const userPhone = currentUser.value.phone ? String(currentUser.value.phone).trim() : ''
  
  return ownerId === userName ||
         ownerId === userPhone ||
         ownerId === userOpenId || 
         ownerId === userSnowflakeId ||
         ownerId === userId
}

// 使用业务逻辑
const {
  fileInputRef,
  inputWrapperRef,
  showEmojiPicker,
  showMentionPicker,
  mentionMembers,
  mentionSearchText,
  isGroupChat,
  handleInputUpdate,
  handleKeyDown,
  handleEnterKey,
  handleMentionSelect,
  closeMentionPicker,
  handleClickOutside,
  toggleEmojiPicker,
  handleFileSelect,
  isImageFile,
  getImagePreviewUrl,
  handleImagePreviewError,
  handleEmojiSelect,
  cleanupPreviewUrls,
} = useMessageInput(props, emit, inputContentRef, mentionPickerRef)

// 生命周期钩子
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
  cleanupPreviewUrls()
})

// 暴露打开群组详情的方法
const openGroupDetails = () => {
  if (props.targetType === 'Group') {
    showGroupDetailsDialog.value = true
  }
}

defineExpose({
  inputContentRef,
  fileInputRef,
  openGroupDetails
})
</script>

<style lang="sass" scoped>
.input-panel
  padding: 8px 12px
  border-top: 1px solid rgba(0, 0, 0, 0.08)
  background: #F7F7F7
  display: flex
  flex-direction: column
  gap: 8px
  box-sizing: border-box
  flex-shrink: 0

  .file-preview
    margin: 0 0 8px 0
    padding: 0
    flex-shrink: 0

    .images-preview-grid
      display: flex
      flex-wrap: wrap
      gap: 8px

    .image-preview-item
      flex-shrink: 0

    .file-chip
      border-radius: 8px
      font-size: 12px
      padding: 6px 12px

    .image-preview-container
      position: relative
      display: inline-block
      max-width: 120px
      max-height: 120px
      width: 120px
      height: 120px
      border-radius: 8px
      overflow: hidden
      border: 1px solid rgba(0, 0, 0, 0.1)
      background: #f5f5f5

      .preview-image
        display: block
        width: 100%
        height: 100%
        object-fit: cover
        cursor: pointer

      .remove-image-btn
        position: absolute
        top: 4px
        right: 4px
        background: rgba(0, 0, 0, 0.6)
        color: white
        width: 24px
        height: 24px
        min-width: 24px
        padding: 0
        
        &:hover
          background: rgba(0, 0, 0, 0.8)

  .toolbar-section
    position: relative
    flex-shrink: 0
    display: flex
    justify-content: space-between
    align-items: center
    margin-bottom: 8px
    padding: 0

    .toolbar-left
      display: flex
      gap: 12px
      align-items: center

    .toolbar-btn
      color: #7A7E89
      width: 28px
      height: 28px
      min-width: 28px
      padding: 0
      border-radius: 0
      background: transparent
      border: none
      transition: opacity 0.2s ease
      
      :deep(.q-icon)
        font-size: 22px
      
      &:hover
        opacity: 0.7
        color: #191919
      
      &:active
        opacity: 0.5

    .emoji-picker-container
      position: absolute
      bottom: 100%
      left: 0
      z-index: 1000
      margin-bottom: 10px

  .input-section
    display: flex
    flex: 1
    min-height: 55px

    .input-wrapper
      flex: 1
      position: relative
      min-width: 0
      width: 100%
      min-height: 55px
      display: flex
      flex-direction: column
      
    .message-input
      width: 100%
      height: 100%
      border-radius: 6px
      flex: 1
      display: flex
      flex-direction: column
      
      :deep(.q-field)
        border-radius: 6px
        height: 100%
        display: flex
        flex-direction: column
        
      :deep(.q-field--standard .q-field__control)
        border: none !important
        border-bottom: none !important
        
      :deep(.q-field--standard.q-field--focused .q-field__control)
        border: none !important
        border-bottom: none !important
        
      :deep(.q-field--standard .q-field__control::before)
        display: none !important
        
      :deep(.q-field--standard .q-field__control::after)
        display: none !important
        
      :deep(.q-field__control-container)
        flex: 1
        display: flex
        flex-direction: column
        min-height: 0
        
      :deep(.q-field__control)
        min-height: 55px
        height: 100%
        max-height: 300px
        font-size: 15px
        border-radius: 6px
        background: #FFFFFF !important
        border: 1px solid rgba(0, 0, 0, 0.1) !important
        transition: border-color 0.2s ease
        flex: 1
        display: flex
        flex-direction: column
        box-shadow: none
        
      :deep(.q-field--focused .q-field__control)
        background: #FFFFFF !important
        border-color: rgba(0, 0, 0, 0.15) !important
        box-shadow: none !important
        
      :deep(.q-field--filled .q-field__control)
        background: #FFFFFF !important
        border: 1px solid rgba(0, 0, 0, 0.1) !important
        box-shadow: none
        
      :deep(.q-field--filled.q-field--focused .q-field__control)
        background: #FFFFFF !important
        border-color: rgba(0, 0, 0, 0.15) !important
        box-shadow: none !important
        
      :deep(.q-field__native)
        min-height: 55px
        height: 100%
        padding: 10px 14px
        line-height: 1.6
        color: #191919
        font-weight: 400
        letter-spacing: 0
        resize: none
        overflow-y: auto
        box-sizing: border-box
        flex: 1
        
      :deep(.q-field__native::placeholder)
        color: #B2B2B2
        font-size: 15px
        
      :deep(.q-field__outline)
        display: none !important
        
      :deep(.q-field__control::before)
        display: none !important
        
      :deep(.q-field__control::after)
        display: none !important
        
      :deep(.q-field__bottom)
        display: none
        
      :deep(.q-field__messages)
        display: none
        
      :deep(.q-field__after)
        display: none
        
      :deep(.q-field__inner)
        border-bottom: none !important
        
      :deep(.q-field__wrapper)
        border-bottom: none !important
        
      :deep(.q-field--filled::after)
        display: none !important
        
      :deep(.q-field--focused::after)
        display: none !important
        
      :deep(.q-field--filled.q-field--focused::after)
        display: none !important

/* 群组详情对话框样式 */
.group-details-dialog
  border-radius: 12px
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12)
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Helvetica Neue", Helvetica, Arial, sans-serif

.dialog-header
  padding: 24px 24px 16px 24px
  border-bottom: 1px solid rgba(0, 0, 0, 0.06)
  display: flex
  align-items: center

.dialog-title
  font-size: 20px
  font-weight: 600
  color: #1D1D1F
  letter-spacing: -0.3px
  line-height: 1.4

.dialog-body
  padding: 20px 24px

.group-info-section
  margin-bottom: 24px
  padding-bottom: 20px
  border-bottom: 1px solid rgba(0, 0, 0, 0.08)

.group-detail-item
  margin-bottom: 16px
  padding-bottom: 12px
  border-bottom: 1px solid rgba(0, 0, 0, 0.06)

  &:last-child
    border-bottom: none
    margin-bottom: 0
    padding-bottom: 0

.detail-label
  font-size: 13px
  color: #666666
  margin-bottom: 4px
  font-weight: 500

.detail-value
  font-size: 15px
  color: #000000
  word-break: break-word

.members-section
  margin-top: 24px

.section-header
  display: flex
  align-items: center
  justify-content: space-between
  margin-bottom: 16px
  gap: 12px

.section-title
  display: flex
  align-items: center
  font-size: 16px
  font-weight: 600
  color: #000000
  letter-spacing: -0.2px

.member-search-input
  flex: 1
  max-width: 250px
  
  :deep(.q-field__control)
    border-radius: 8px
    border: 1px solid rgba(226, 232, 240, 0.8)
    background: #f8fafc
    transition: all 0.3s ease
  
  :deep(.q-field--focused .q-field__control)
    border-color: #7c3aed
    background: #FFFFFF
    box-shadow: 0 0 0 3px rgba(124, 58, 237, 0.12)
  
  :deep(.q-field__native)
    font-size: 14px
    color: #1D1D1F

.members-list
  max-height: 400px
  overflow-y: auto
  border: 1px solid rgba(0, 0, 0, 0.06)
  border-radius: 8px
  background: #fafbfc
  padding: 8px

.members-list::-webkit-scrollbar
  width: 6px
  height: 6px

.members-list::-webkit-scrollbar-track
  background: transparent
  border-radius: 3px

.members-list::-webkit-scrollbar-thumb
  background: rgba(0, 0, 0, 0.2)
  border-radius: 3px
  transition: background 0.2s ease

.members-list::-webkit-scrollbar-thumb:hover
  background: rgba(0, 0, 0, 0.3)

.empty-members
  padding: 40px 20px
  text-align: center
  color: #666666

.loading-members
  padding: 40px 20px
  text-align: center
  display: flex
  flex-direction: column
  align-items: center
  gap: 16px

.loading-text
  color: #666666
  font-size: 14px

.member-item-detail
  display: flex
  align-items: center
  padding: 12px
  gap: 12px
  border-radius: 8px
  transition: background-color 0.2s ease
  margin-bottom: 4px

  &:hover
    background-color: rgba(255, 255, 255, 0.8)

.member-avatar-detail
  flex-shrink: 0

  .avatar-placeholder
    width: 100%
    height: 100%
    display: flex
    align-items: center
    justify-content: center
    background: #C9C9C9
    color: white
    font-weight: 500
    border: 1px solid #E5E5E5
    font-size: 16px
    border-radius: 50%

.member-info-detail
  flex: 1
  min-width: 0
  overflow: hidden

.member-name-detail
  font-size: 15px
  font-weight: 500
  color: #000000
  margin-bottom: 4px
  display: flex
  align-items: center
  overflow: hidden
  text-overflow: ellipsis
  white-space: nowrap

.member-id-detail
  font-size: 13px
  color: #666666
  overflow: hidden
  text-overflow: ellipsis
  white-space: nowrap

.dialog-actions-bottom
  padding: 16px 24px
  display: flex
  align-items: center
  gap: 12px

.dialog-btn
  font-size: 15px
  font-weight: 500
  padding: 8px 16px
  min-width: 64px
  letter-spacing: -0.1px
</style>

